package com.zhilianbao.leyaogo.ui.fragment.address;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.utils.AsyncTaskUtils;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AddressApi;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.address.Address;
import com.zhilianbao.leyaogo.ui.adapter.shoppingcart.ReceiveAddressAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.RefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.zhilianbao.leyaogo.constants.IntentConfig.KEY_LAST_ID;
import static com.zhilianbao.leyaogo.constants.IntentConfig.KEY_SELECT;

/**
 * Author: hcy
 * Description:收货地址
 * Created: 2016/10/24 17:54
 */
public class ReceiveAddressFragment extends RefreshAndLoadFragment<Address> implements ReceiveAddressAdapter.OnModifyClickListener, ReceiveAddressAdapter.OnCheckBoxClickListener{

    @BindView(R.id.tv_add_address)
    public TextView mAddAddressTv;

    @BindView(R.id.bottom_view)
    LinearLayout mBottomView;

    private long lastId;
    private boolean isSelect;

    private ReceiveAddressAdapter mAdapter;


    public static ReceiveAddressFragment getInstance(boolean isSelect) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(KEY_SELECT, isSelect);
        ReceiveAddressFragment fragment = new ReceiveAddressFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public static ReceiveAddressFragment getInstance(boolean isSelect, long lastId) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(KEY_SELECT, isSelect);
        bundle.putLong(KEY_LAST_ID, lastId);
        ReceiveAddressFragment fragment = new ReceiveAddressFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_receive_address;
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(mActivity.getResources().getString(R.string.receive_address));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        isSelect = getArguments().getBoolean(KEY_SELECT, true);
        lastId =  getArguments().getLong(KEY_LAST_ID, -1);
        mAdapter = new ReceiveAddressAdapter(mActivity, mList);
        mAdapter.setLastId(lastId);
        mAdapter.setModifyListener(this);
        mAdapter.setOnCheckBoxClickListener(this);
        mRcvLoadMore.setHideLoadingView(true);
        mRcvLoadMore.setCanLoadMore(false);
        mAddAddressTv.setEnabled(false);
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        doClick(position);
    }

    private void doClick(final int position) {
        if (isSelect) {
            ThreadPool.postOnUiDelayed(() -> EventBus.getDefault().post(new EventManager<>(LeEventCode.MSG_CODE_MODIFY_SEL_ADDRESS, mList.get(position))), 300);
            pop();
        }
    }

    @Override
    public QuickRcvAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }


    @Override
    public void onRefresh() {
        loadDataList(mCurPage, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        long userId = Utils.getUserLoginInfo().getUserId();
        long supplierId = Utils.getSupplierId();
        AddressApi.getAddress(mActivity, userId, supplierId, 0, new RefreshAndLoadCallback<List<Address>>(isPullToRefresh) {

            @Override
            public void errorLeftOrEmptyBtnClick(View view) {
                loadDataList(mCurPage, false);
            }

            @Override
            public void onResultSuccess(List<Address> addresses, @Nullable Response response, LoadingViewCallback callback) {
                setBottomViewBg(addresses != null && addresses.size() > 0);
                handleRefreshAndLoadListData(1, callback, addresses);
                if (addresses != null && addresses.size() > 0) {
                    isNeedSaveDefaultAddress(addresses);
                }
                if(addresses != null && addresses.size() < 5){
                    mAddAddressTv.setEnabled(true);
                }else {
                    mAddAddressTv.setEnabled(false);
                }
            }

            @Override
            public Drawable emptyDrawable() {
                return getResources().getDrawable(R.drawable.empty_address);
            }

            @Override
            public String emptyContent() {
                return getString(R.string.address_empty_hint);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mAddAddressTv.setEnabled(false);

            }
        });


    }

    /**
     * 设置底部背景应为要区分有数据无数据）
     */
    private void setBottomViewBg(boolean haveData) {
        if(mBottomView==null){
            return;
        }
        mBottomView.setBackgroundColor(haveData ? getResources().getColor(R.color.white) : getResources().getColor(R.color.color_f5f5f5));
    }

    @Override
    public void onLoadMore() {

    }

    @OnClick(R.id.tv_add_address)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add_address:
                if (mList.size() >= 5) {
                    XToastUtils.showShortToast(getString(R.string.modify_limit_5));
                    return;
                }
                start(ModifyAddressFragment.getInstance(false, null));
                break;
        }
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_MODIFY_ADDRESS || eventManager.getEventCode() == LeEventCode.MSG_CODE_MODIFY_DEL_ADDRESS) {
            Address address = (Address) eventManager.getData();
            if(address!=null&&address.getIsDefault()==1){
                lastId = address.getAddressId();
                mAdapter.setLastId(lastId);
            }
            loadDataList(mCurPage, true);
        }
    }

    /**
     * 编辑收获地址
     *
     * @param pos
     */
    @Override
    public void modify(int pos) {
        start(ModifyAddressFragment.getInstance(true, mList.get(pos)));
    }

    /**
     * 是否需要保存默认地址（列表有默认地址，但是sp存储为空）
     */
    private void isNeedSaveDefaultAddress(List<Address> addresses) {
        AsyncTaskUtils.exe(new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                if (CheckUtils.isNull(Utils.getDefaultAddress())) {
                    for (Address address : addresses) {
                        if (address.getIsDefault() == 1) {
                            Utils.putDefaultAddress(address);
                            break;
                        }
                    }
                }
                return null;
            }
        });
    }


    @Override
    public void onCheckClick(int pos) {
        doClick(pos);
    }

    @Override
    public void leftContainerClick() {
        super.leftContainerClick();
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_RECEIVE_ADDRESS_FRAGMENT_BACK));
    }
}
